﻿using Mangix.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mangix.Mapping.Setting;
using Mangix.Core.Caching;
using Mangix.Mapping;

namespace Mangix.Services.Setting
{
    public class SettingService : ISettingService
    {
        private const string MODEL_KEY = "Mangix.service.setting";
        private IRepository<Entities.Setting> _settingRepository;
        private ICacheManager _cacheManager;
        public SettingService(IRepository<Entities.Setting> settingRepository,
            ICacheManager cacheManager)
        {
            this._settingRepository = settingRepository;
            this._cacheManager = cacheManager;
        }

        /// <summary>
        /// 获取所有数据并缓存
        /// </summary>
        /// <returns></returns>
        public List<SettingMapping> getAllCache()
        {
            return _cacheManager.get(MODEL_KEY, () =>
            {
                var result = _settingRepository.Table.ToList();
                if (result.Any())
                    return result.Select(item => item.toModel()).ToList();
                return null;
            });
        }

        /// <summary>
        /// 通过名称获取
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public SettingMapping getByName(string name)
        {
            var list = getAllCache();
            if (list == null)
                return null;
            return list.FirstOrDefault(o => o.Name == name);
        }
         

         
    }
}
